package com.spring.lesson001.demo4;

import org.springframework.beans.factory.ObjectFactory;
import org.springframework.beans.factory.config.Scope;
import org.springframework.lang.Nullable;

import java.util.HashMap;
import java.util.Map;
import java.util.Objects;

/**
 * @author vhans
 */
public class ThreadScope implements Scope {
    public static final String THREAD_SCOPE = "thread";

    private ThreadLocal<Map<String, Object>> beanMap = new ThreadLocal() {
        // 设置beanMap的初始内容，在调用get()方法时被执行
        @Override
        protected Object initialValue() {
            return new HashMap<>();
        }
    };

    @Override
    public Object get(String s, ObjectFactory<?> objectFactory) {
        Object bean = beanMap.get().get(s);
        if (Objects.isNull(bean)) {
            bean = objectFactory.getObject();
            beanMap.get().put(s, bean);
        }
        return bean;
    }

    @Override
    @Nullable
    public Object remove(String s) {
        return this.beanMap.get().remove(s);
    }

    @Override
    public void registerDestructionCallback(String s, Runnable runnable) {
        // bean作用域范围结束的时候调用的方法，用于bean清理
        System.out.println(s);
    }

    @Override
    @Nullable
    public Object resolveContextualObject(String s) {
        return null;
    }

    @Override
    @Nullable
    public String getConversationId() {
        return Thread.currentThread().getName();
    }
}
